<?php

namespace App\Console\Commands;

use Illuminate\Console\GeneratorCommand;
use Illuminate\Support\Facades\Schema;

class Models extends GeneratorCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'make:export-model {table} {--name=} {--path=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '生成App/Models目录下文件';

    protected function getStub()
    {
        return __DIR__ . '/stubs/models.stub';
    }

    protected function getDefaultNamespace($rootNamespace)
    {
        $path = $this->option('path');
        if ($path) {
            return $rootNamespace . '\\' . $path;
        }
        return $rootNamespace . '\Models';
    }

    /**
     * Execute the console command.
     * @return bool|null
     * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
     */
    public function handle()
    {
        //获取拼接命名空间后的全称
        $table = trim($this->argument('table'));
        $name  = $this->option('name') ?? ucfirst($table);

        $qualify_name = $this->qualifyClass($name);
        //获取文件的实际存储路径
        $path = $this->getPath($qualify_name);

        //若文件已存在，直接给出错误提示而不会覆盖原来的文件
        if ($this->alreadyExists($path)) {
            $this->error($path . ' already exists!');
            return false;
        }
        //生成文件
        $this->makeDirectory($path);
        //适当地替换模版文件中的数据，如命名空间和类名
        $stub   = $this->files->get($this->getStub());
        $fields = json_encode(Schema::getColumnListing($table));

        // 替换命名空间类名
        $model = $this->replaceNamespace($stub, $name)->replaceClass($stub, $qualify_name);
        // 替换表名
        $model = str_replace('table_name', $table, $model);
        // 填充fillable
        $model = str_replace('fields', $fields, $model);

        $this->files->put($path, $model);

        $this->info("OK，执行完成...");
    }
}
